#pragma once
#include "../comm/httplib.h"
#include <string>
#include <mysql/mysql.h>
#include "head_mysql.hpp"

#include"../comm/log.hpp"

using namespace ns_log;

// 验证 session_id 是否在数据库中有效
bool is_valid_session(const std::string &session_id) {
    // 连接到数据库
    MYSQL *conn = connect_db();
    if (conn == nullptr) {
        LOG(ERROR)<< "Database connection failed" << std::endl;
        return false;
    }

    // 构建 SQL 查询，查找 session_id 是否存在
    std::string query = "SELECT COUNT(*) FROM users WHERE session_id = '" + session_id + "'";

    if (mysql_query(conn, query.c_str())) {
        LOG(ERROR)<< "Query execution failed: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return false;
    }

    MYSQL_RES *result = mysql_store_result(conn);
    if (result == nullptr) {
         LOG(ERROR)<< "Result retrieval failed: " << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return false;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    bool is_valid = row && std::stoi(row[0]) > 0;

    // 清理
    mysql_free_result(result);
    mysql_close(conn);

    return is_valid;
}

// 检查请求中的 Cookie
bool check_cookie(const httplib::Request &req) {
    auto cookies = req.get_header_value("Cookie");
    std::string session_id;

    size_t pos = cookies.find("sessionid=");
    if (pos != std::string::npos) {
        size_t start = pos + strlen("sessionid=");
        size_t end = cookies.find(';', start);
        if (end == std::string::npos) {
            end = cookies.length();
        }
        session_id = cookies.substr(start, end - start);
    }

    LOG(INFO)<< "session_id: " << session_id << std::endl;
    return !session_id.empty() && is_valid_session(session_id);
}
